export function formatDate(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + '';
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
    }
  }
  return fmt;
}

function padLeftZero(str) {
  return ('00' + str).substr(str.length);
}

export function setDate(date, format, style = true) {
  let time = new Date(date);
  let val = '';
  if (style) {
    switch (format) {
      case 'yy-mm':
        val = `${time.getFullYear()}-${time.getMonth() + 1}`;
        break;
      case 'yy-mm-dd':
        val = `${time.getFullYear()}-${time.getMonth() + 1}-${zero(time.getDate())}`;
        break;
      case 'yy-mm-dd-hh-ii':
        val = `${time.getFullYear()}-${time.getMonth() + 1}-${zero(time.getDate())}  ${zero(time.getHours())}:${zero(time.getMinutes())}`;
        break;
      case 'hh-ii':
        val = `${zero(time.getHours())}:${zero(time.getMinutes())}`;
        break;
      case 'hh-ii-ss':
        val = `${zero(time.getHours())}:${zero(time.getMinutes())}:${zero(time.getSeconds())}`;
        break;
    }
    return val
  } else {
    switch (format) {
      case 'yy-mm':
        val = `${time.getFullYear()}年${time.getMonth() + 1}月`;
        break;
      case 'yy-mm-dd':
        val = `${time.getFullYear()}年${time.getMonth() + 1}月${zero(time.getDate())}日`;
        break;
      case 'yy-mm-dd-hh-ii':
        val = `${time.getFullYear()}年${time.getMonth() + 1}月${zero(time.getDate())}日${zero(time.getHours())}:${zero(time.getMinutes())}`;
        break;
      case 'hh-ii':
        val = `${zero(time.getHours())}:${zero(time.getMinutes())}`;
        break;
      case 'hh-ii-ss':
        val = `${zero(time.getHours())}:${zero(time.getMinutes())}:${zero(time.getSeconds())}`;
        break;
    }
    return val
  }

}

export function formatDuring(mss) {
  if (mss <= 0) {
    return `0天0小时0分`
  }
  let day = zero(parseInt(mss / (1000 * 60 * 60 * 24)));
  let hours = zero(parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)));
  let minutes = zero(parseInt((mss % (1000 * 60 * 60)) / (1000 * 60)));
  let seconds = ((zero((mss % (1000 * 60)) / 1000)) + '').split('.')[0];
  return `${day}天${hours}小时${minutes}分`
}


function zero(num) {
  if (num < 10) {
    return '0' + num
  } else {
    return num
  }
}